/*
Copyright 2009 Johan Maasing, Mikael Forsberg

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.code.pj2r.resources;

import com.google.code.pj2r.Resource;
import com.google.code.pj2r.ResourceCreationException;
import com.google.code.pj2r.ResourceFactory;

public class ResourceFactoryImpl implements ResourceFactory {

    private final String packageName;

    public ResourceFactoryImpl(final String packageName) {
        String pname = packageName;
        if (!packageName.endsWith(".")) {
            pname = pname + ".";
        }
        this.packageName = pname;
    }

    @Override
    public Resource getResource(String name) throws ResourceCreationException {
        Resource resource;

        Class<? extends Resource> resourceClass;
        try {
            resourceClass = Class.forName(packageName + name).asSubclass(Resource.class);
            resource = resourceClass.newInstance();
        } catch (ClassNotFoundException ex) {
            throw new ResourceCreationException(ex);
        } catch (InstantiationException ex) {
            throw new ResourceCreationException(ex);
        } catch (IllegalAccessException ex) {
            throw new ResourceCreationException(ex);
        }

        return resource;
    }
}
